import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../model/base_response.dart';
import '../model/wallet_model.dart';
import '../service/wallet_service.dart';
import 'auth_controller.dart';

class WalletController extends GetxController {
  final WalletService _walletService = WalletService();
  final AuthController _authController = Get.find<AuthController>();

  // 用户收益数据
  var userEarningsResponse = Rx<UserEarningsResponse?>(null);
  var isLoadingEarnings = false.obs;

  // 提现记录数据
  var withdrawRecordsResponse = Rx<WithdrawRecordsResponse?>(null);
  var isLoadingWithdrawRecords = false.obs;

  // 提现页面数据
  var withdrawPageData = Rx<WithdrawPageDataResponse?>(null);
  var isLoadingWithdrawPageData = false.obs;

  // 近期记录（合并收益和提现记录）
  var recentRecords = <RecentRecordModel>[].obs;
  var isLoadingRecentRecords = false.obs;

  // 提现申请状态
  var isSubmittingWithdraw = false.obs;
  var isSendingVerificationCode = false.obs;

  @override
  void onInit() {
    super.onInit();
  }

  /// 加载所有钱包数据
  Future<void> loadAllWalletData() async {
    await Future.wait([
      loadUserEarnings(),
      // loadWithdrawRecords(),
      loadWithdrawPageData(),
    ]);
    _buildRecentRecords();
  }

  /// 加载用户收益数据
  Future<void> loadUserEarnings() async {
    try {
      isLoadingEarnings.value = true;
      final response = await _walletService.getUserEarnings();

      if (response.success && response.data != null) {
        userEarningsResponse.value = UserEarningsResponse.fromJson(
            response.data! as Map<String, dynamic>);
        // 更新AuthController中的BTC余额
        _authController.btcBalance.value =
            userEarningsResponse.value!.btcNumValue;
        // print('获取收益数据成功 : ${userEarningsResponse.value!.btcNumValue}');
      } else {
        _showErrorMessage('Data Error', response.message);
        // print('获取收益数据失败 : ${response.message}');
      }
    } catch (e) {
      _showErrorMessage('Data Error', e.toString());
    } finally {
      isLoadingEarnings.value = false;
    }
  }

  /// 加载提现记录
  Future<void> loadWithdrawRecords() async {
    try {
      isLoadingWithdrawRecords.value = true;
      final response = await _walletService.getWithdrawRecords();

      if (response.success && response.data != null) {
        withdrawRecordsResponse.value = WithdrawRecordsResponse.fromJson(
            response.data! as Map<String, dynamic>);
      } else {
        _showErrorMessage(
            'Loading withdraw records failed'.tr, response.message);
      }
    } catch (e) {
      _showErrorMessage('Loading withdraw records failed'.tr, e.toString());
    } finally {
      isLoadingWithdrawRecords.value = false;
    }
  }

  Future<BaseResponse<Map<String, dynamic>>> submitWithdrawRequest({
    required String amount,
    required String address,
    required int networkId,
  }) async {
    try {
      final response = await _walletService.submitWithdrawRequest(
        amount,
        address,
        networkId,
      );
      if (response.success) {
        // 刷新用户余额
        await loadAllWalletData();
      }
      return response;
    } catch (e) {
      return BaseResponse<Map<String, dynamic>>(
        success: false,
        message: e.toString(),
        code: -1,
      );
    }
  }

  /// 加载提现页面数据
  Future<void> loadWithdrawPageData() async {
    try {
      isLoadingWithdrawPageData.value = true;
      final response = await _walletService.getWithdrawPageData();

      if (response.success && response.data != null) {
        withdrawPageData.value =
            WithdrawPageDataResponse.fromJson(response.data!);
      } else {
        _showErrorMessage(
            'Loading withdraw records failed'.tr, response.message);
      }
    } catch (e) {
      _showErrorMessage('Loading withdraw records failed'.tr, e.toString());
    } finally {
      isLoadingWithdrawPageData.value = false;
    }
  }

  /// 构建近期记录（合并收益和提现记录）
  void _buildRecentRecords() {
    final List<RecentRecordModel> records = [];

    // 添加收益记录
    if (userEarningsResponse.value != null) {
      for (final earning in userEarningsResponse.value!.list) {
        records.add(RecentRecordModel.fromEarning(earning));
      }
    }

    // 添加提现记录
    // if (withdrawRecordsResponse.value != null) {
    //   for (final withdraw in withdrawRecordsResponse.value!.list) {
    //     records.add(RecentRecordModel.fromWithdraw(withdraw));
    //   }
    // }

    // 按时间排序（最新的在前）
    records.sort((a, b) => b.dateTime.compareTo(a.dateTime));

    recentRecords.value = records;
  }

  /// 刷新所有数据
  Future<void> refreshAllData() async {
    isLoadingRecentRecords.value = true;
    await loadAllWalletData();
    isLoadingRecentRecords.value = false;
  }

  // 计算属性
  String get availableBalance =>
      userEarningsResponse.value?.btcNumValue ?? '0.00000000';
  List<NetworkConfigModel> get availableNetworks =>
      withdrawPageData.value?.network.where((n) => n.isAvailable).toList() ??
      [];

  // 获取指定网络的配置
  NetworkConfigModel? getNetworkConfig(int networkId) {
    return withdrawPageData.value?.network
        .firstWhereOrNull((n) => n.id == networkId);
  }

  // 获取最小提现金额
  double getMinWithdrawAmount(int networkId) {
    final config = getNetworkConfig(networkId);
    return config?.minimumAmountValue ?? 0.0006;
  }

  // 详情页面响应对象
  var detailUserEarningsResponse = Rx<UserEarningsResponse?>(null);
  var detailWithdrawRecordsResponse = Rx<WithdrawRecordsResponse?>(null);

  // 详情页面分页数据
  var detailIncomeRecords = <RecentRecordModel>[].obs;
  var detailWithdrawRecords = <RecentRecordModel>[].obs;
  var isLoadingDetailIncomeRecords = false.obs;
  var isLoadingDetailWithdrawRecords = false.obs;
  var hasMoreIncomeRecords = true.obs;
  var hasMoreWithdrawRecords = true.obs;

  /// 加载详情页收益记录（分页）
  Future<void> loadDetailIncomeRecords(
      {int page = 1, int pageSize = 20, bool showLoading = true}) async {
    try {
      if (page == 1 && showLoading) {
        isLoadingDetailIncomeRecords.value = true;
      }

      final response =
          await _walletService.getUserEarnings(page: page, pageSize: pageSize);

      if (response.success && response.data != null) {
        final earningsResponse = UserEarningsResponse.fromJson(
            response.data! as Map<String, dynamic>);
        detailUserEarningsResponse.value = earningsResponse;
        final List<RecentRecordModel> records = [];

        for (final earning in earningsResponse.list) {
          records.add(RecentRecordModel.fromEarning(earning));
        }

        if (page == 1) {
          detailIncomeRecords.value = records;
        } else {
          detailIncomeRecords.addAll(records);
        }

        // 判断是否还有更多数据
        hasMoreIncomeRecords.value = records.length >= pageSize;
      } else {
        if (page == 1) {
          detailIncomeRecords.clear();
        }
        _showErrorMessage('Loading withdraw records failed', response.message);
      }
    } catch (e) {
      if (page == 1) {
        detailIncomeRecords.clear();
      }
      _showErrorMessage('Loading withdraw records failed', e.toString());
    } finally {
      isLoadingDetailIncomeRecords.value = false;
    }
  }

  /// 加载详情页提现记录（分页）
  Future<void> loadDetailWithdrawRecords(
      {int page = 1, int pageSize = 20, bool showLoading = true}) async {
    try {
      if (page == 1 && showLoading) {
        isLoadingDetailWithdrawRecords.value = true;
      }

      final response = await _walletService.getWithdrawRecords(
          page: page, pageSize: pageSize);

      if (response.success && response.data != null) {
        final withdrawResponse = WithdrawRecordsResponse.fromJson(
            response.data! as Map<String, dynamic>);
        detailWithdrawRecordsResponse.value = withdrawResponse;
        final List<RecentRecordModel> records = [];

        for (final withdraw in withdrawResponse.list) {
          RecentRecordModel withdrawData =
              RecentRecordModel.fromWithdraw(withdraw);
          withdrawData.title = withdrawData.statusTitle;
          records.add(withdrawData);
        }

        if (page == 1) {
          detailWithdrawRecords.value = records;
        } else {
          detailWithdrawRecords.addAll(records);
        }

        // 判断是否还有更多数据
        hasMoreWithdrawRecords.value = records.length >= pageSize;
      } else {
        if (page == 1) {
          detailWithdrawRecords.clear();
        }
        _showErrorMessage('Loading withdraw records failed', response.message);
      }
    } catch (e) {
      if (page == 1) {
        detailWithdrawRecords.clear();
      }
      _showErrorMessage('Loading withdraw records failed', e.toString());
    } finally {
      isLoadingDetailWithdrawRecords.value = false;
    }
  }

  /// 刷新详情页数据
  Future<void> refreshDetailData() async {
    await Future.wait([
      loadDetailIncomeRecords(page: 1, showLoading: false),
      loadDetailWithdrawRecords(page: 1, showLoading: false),
    ]);
  }

  // 获取网络费用
  double getNetworkFee(int networkId) {
    final config = getNetworkConfig(networkId);
    return config?.networkFeeValue ?? 0.00015;
  }

  /// 显示错误消息
  void _showErrorMessage(String title, String? message) {
    Get.snackbar(
      title,
      message ?? 'Error',
      backgroundColor: Colors.red,
      colorText: Colors.white,
      snackPosition: SnackPosition.TOP,
      margin: EdgeInsets.all(16),
      borderRadius: 12,
      duration: Duration(seconds: 3),
    );
  }
}
